import 'package:flutter/material.dart';
import 'package:haitao_app/InfoDetail.dart';
import 'config/config.dart';
import 'view/LinePaint.dart';
import 'table/resp_result.dart';
import 'config/http_util.dart';


class Haitao extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return HaitaoWidget();
  }
}

class HaitaoWidget extends State<Haitao>{

  GlobalKey<ScaffoldState> _globalKey=GlobalKey();
  List<RstData> listdata;
  int pager=1;
  int divid_id=5685521;
  String connection="";
  String lastType="";
  String apptitle="海淘";
  ScrollController scrollController=ScrollController();

  HaitaoWidget(){
    scrollController.addListener((){
      var max=scrollController.position.maxScrollExtent;
      var posion=scrollController.position.pixels;
      if(posion==max){
        pager++;
        if(listdata!=null && listdata.length>0){
          divid_id=listdata[listdata.length-1].id;
        }
        _getServerData("sinceid=$divid_id$connection");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(apptitle,style: TextStyle(color: Colors.white),),
        backgroundColor: Color.fromARGB(255, 0, 175, 0),
        leading: IconButton(icon: Icon(Icons.menu,color: Colors.white,), onPressed: _drawerChange),
      ),
      body: _body(),
    );
  }

  void _drawerChange(){
    if(_globalKey.currentState.isDrawerOpen){
      _globalKey.currentState.openEndDrawer();
    }else{
      _globalKey.currentState.openDrawer();
    }
  }

  Widget _body(){
    return Scaffold(
      key: _globalKey,
      drawer: _drawer(),
      body: _center(),
    );
  }

  Widget _drawer(){
    var type=haitao_type;
    return Container(
      width: 200,
      color: Colors.white,
      child: ListView.builder(
          itemCount: type.length,
          itemBuilder: (content,index){
            return _drawerItem(type[index]);
          }
      ),
    );
  }

  Widget _drawerItem(Map<String,String> map){
    if(map["title"]=="=="){
      return Container(
        height: 1,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.black54)
        ),
      );
    }else{
      return GestureDetector(
        child: Container(
          padding: EdgeInsets.only(left: 10,top: 8,bottom: 8),
          child: Text(map["title"]),
        ),
        onTap: (){
          //单击事件
          _onDrawerItemClick(map);
        },
      );
    }
  }
  void _onDrawerItemClick(Map<String,String> map){
    print(map.toString());
    if(lastType!=map["type"]) {
      pager = 1;
      String t = "";
      if (map["type"] == "all") {
        connection = "";
      } else {
        t = "-" + map["title"];
        if (map["type"] == "hot") {
          connection = "&onlyhots=1";
        } else if (map["type"] == "mall") {
          connection = "&mall=${map["mall"]}";
        } else if (map["type"] == "cate") {
          connection = "&cate=${map["cate"]}";
        }
      }
      _getServerData("markid=$divid_id$connection");
      setState(() {
        apptitle = "首页" + t;
      });
    }
    _drawerChange();
  }

  Widget _center(){
    Widget listview=ListView.builder(
      itemCount: listdata!=null?listdata.length:0,
      itemBuilder: (content,index){
        return _centerItem(listdata[index]);
      },
      controller: scrollController,
    );
    return RefreshIndicator(
      child: listview,
      onRefresh: onRefresh,
    );
  }

  Future<Null> onRefresh() async{
    pager=1;
    if(listdata!=null && listdata.length>0){
      divid_id=listdata[0].id;
    }
    _getServerData("markid=$divid_id$connection");
    return null;
  }

  Widget _centerItem(RstData data){
    return SizedBox(
      height: 110,
      child: GestureDetector(
        child: Container(
          margin: EdgeInsets.all(5),
          padding: EdgeInsets.only(left: 5,top: 5,bottom: 5,right: 5),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.black54),
            borderRadius: BorderRadius.all(Radius.circular(5)),
          ),
          child: Row(
            children: <Widget>[
              Container(
                width: 100,
                height: 100,
                child: Image.network(data.image),
              ),
              Expanded(
                child: Column(
                  children: <Widget>[
                    Text(data.title),
                    Expanded(
                      child: Container(
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              flex: 1,
                              child: Container(
                                alignment: Alignment.bottomLeft,
                                child: Text(data.mall,style: TextStyle(color: Color.fromARGB(255, 0, 175, 0),fontSize: 12),),
                              ),
                            ),
                            Expanded(
                              flex: 2,
                              child: Container(
                                alignment: Alignment.bottomRight,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: <Widget>[
                                    Text("${data.fromsite}·",style: TextStyle(color: Colors.grey,fontSize: 10),),
                                    _pubtime(data.pubtime),
//                                    Text(data.pubtime,style: TextStyle(color: Color.fromARGB(255, 0, 175, 0),fontSize: 10),),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        onTap: (){_itemClick(data);},
      ),
    );
  }

  Widget _pubtime(String pubtime){
    DateTime dateTime=DateTime.now();
    DateTime time=DateTime.parse(pubtime);
    double pubt=(dateTime.millisecond-time.millisecond)/1;
    String string="";
//    if(pubt<1000){
//      string = "1秒前";
//    }else {
      if (pubt < 60) {
        string = "${int.parse(pubt.toStringAsFixed(0))}秒前";
      } else {
        pubt = pubt / 60;
        if (pubt < 60) {
          string = "${int.parse(pubt.toStringAsFixed(0))}分钟前";
        } else {
          pubt = pubt / 60;
          if (pubt <= 24) {
            string = "${int.parse(pubt.toStringAsFixed(0))}小时前";
          } else {
            pubt = pubt / 24;
            string = "${int.parse(pubt.toStringAsFixed(0))}天前";
          }
        }
      }
//    }
    return Text(string,style: TextStyle(color: Color.fromARGB(255, 0, 175, 0),fontSize: 10),);
  }

  void _itemClick(RstData data){
    Navigator.push(context, MaterialPageRoute(builder: (context)=>InfoDetail(id:data.id,title: data.title,)));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getServerData("markid=$divid_id$connection");
  }

  void _getServerData(String connection){
    HttpUtil().get("/getlist.php?$connection&country=us",options: HttpUtil().options)
        .then((resp){
      RespResult result=RespResult.fromJson(resp.data);
      print(result.toString());
      var data=listdata;
      if(data==null){
        data=result.data;
      }else{
        if(pager==1){
          data.clear();
        }
        data.addAll(result.data);
      }
      setState(() {
        listdata=data;
      });
    });
  }
  
}